package com.mybeautysalon.controller;

import com.mybeautysalon.dao.MemberMapper;
import com.mybeautysalon.dataobject.Member;
import com.mybeautysalon.dataobject.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yunfei
 * @Date: 22:39
 */
@Controller
public class MemberControl {
    @Autowired
    private MemberMapper memberMapper;
    private String messages;
    private Member me;
    @RequestMapping(path = "/insert_mem")
    public String insertMem(Member member, @RequestParam("ser_mem") String id, ModelMap modelMap) {
//        先判断是否存在
        if (memberMapper.selectByPrimaryKey(Integer.valueOf(id)) != null) {
            messages = "data has already exist";

        } else {
            memberMapper.insert(member);
            messages = "insert success!";

        }
        modelMap.addAttribute("messages", messages);
        return "response";

    }

    @RequestMapping(path="/del_mem")
    public String delMem(@RequestParam("mem_id") String id, ModelMap modelMap) {
//        判断是否存在
        if (memberMapper.selectByPrimaryKey(Integer.valueOf(id)) != null) {
            messages = "data has already exist";

        } else {
            memberMapper.deleteByPrimaryKey(Integer.valueOf(id));
            messages = "delete success!";
        }

        modelMap.addAttribute("messages", messages);
        return "response";
    }

    @RequestMapping("/update_mem")
    public String updateMem(@RequestParam("mem_id") String id, Member  member, ModelMap modelMap) {
        if (memberMapper.selectByPrimaryKey(Integer.valueOf(id)) != null) {
            memberMapper.updateByPrimaryKey(member);
            messages = "update success!";
        } else {
            messages = "the data doesn't exist,can't update";
        }
        modelMap.addAttribute("messages", messages);
        return "reponse";
    }

    @RequestMapping("/select_mem_id")
    public String selectMem(@RequestParam("mem_id") String id, ModelMap modelMap) {
        List<Member> list = new ArrayList<>();
        me = memberMapper.selectByPrimaryKey(Integer.valueOf(id));
        list.add(me);

        if (me != null) {

            modelMap.addAttribute("me", me);
            return "sel_mem";

        } else {
            messages = "id doesn't exist";
            modelMap.addAttribute("messages", messages);
            return "response";

        }

    }

    @RequestMapping(path = "/query_mem")
    @ResponseBody
    public String query(){
        List<Member> lists;
        lists= memberMapper.selectAll();
        return StringUtils.strip(lists.toString(),"[]");
    }

}
